package hit.example.home;

import hit.example.Json.ServiceHandler;
import hit.example.Object.ObjVietAnh;
import hit.example.adapter.AdapterSearchVietAnh;
import hit.example.hitdict.R;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

public class SearchVietAnhFm extends MyFragment {
	EditText edtSearchVA;
	ImageButton btnSearchVA;
	ListView lvShowVA;
	View v;

	private ProgressDialog pDialog;
	JSONArray sentences = null;
	// JSON Node names
	private static final String TAG_CONTACTS = "sentences";
	private static final String TAG_ID = "_id";
	private static final String TAG_FIELDS = "fields";
	private static final String TAG_FIELDS_VI = "vi";
	private static final String TAG_FIELDS_EN = "en";

	ArrayList<ObjVietAnh> list;
	AdapterSearchVietAnh adp;

	public static SearchVietAnhFm getInstance() {
		SearchVietAnhFm sva = new SearchVietAnhFm();
		return sva;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		v = inflater.inflate(R.layout.fm_seachvietanh, container, false);
		edtSearchVA = (EditText) v.findViewById(R.id.edtSearchVA);
		btnSearchVA = (ImageButton) v.findViewById(R.id.btnSearchVA);
		lvShowVA = (ListView) v.findViewById(R.id.lvShowVA);
		HomeActivity.getInstance().setHide();
		HomeActivity.getInstance().changeTitle("Tra câu Việt - Anh");
		return v;

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		btnSearchVA.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String input = edtSearchVA.getText().toString();
				if (input.trim().length() == 0) {

				} else {
					HomeActivity.getInstance().hiddenInput();
					new GetSentences().execute(input);
				}

			}
		});
	}

	private class GetSentences extends AsyncTask<String, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		protected Void doInBackground(String... text) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();
			String url = "http://tracau.vn:1981/WBBcwnwQpV89/" + text[0]
					+ "/vi/JSON_CALLBACK";
			url = url.replace(" ", "%20");

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
			jsonStr = jsonStr.replace("JSON_CALLBACK(", "");
			jsonStr = jsonStr.replace(");", "");
			try {
				jsonStr = new String(jsonStr.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);

					// Getting JSON Array node
					sentences = jsonObj.getJSONArray(TAG_CONTACTS);
					list = new ArrayList<ObjVietAnh>();
					// looping through All Contacts
					for (int i = 0; i < sentences.length(); i++) {
						JSONObject c = sentences.getJSONObject(i);

						String id = c.getString(TAG_ID);

						// Phone node is JSON Object
						JSONObject fields = c.getJSONObject(TAG_FIELDS);
						String en = fields.getString(TAG_FIELDS_EN);
						String vi = fields.getString(TAG_FIELDS_VI);
						// vi=vi.replace("em", "");
						vi = vi.replace("<em>", "");
						vi = vi.replace("</em>", "");

						ObjVietAnh obj = new ObjVietAnh();
						obj.setId(id);
						obj.setEn(en);
						obj.setVi(vi);
						Log.i("dinhtv", vi);
						// adding contact to contact list
						list.add(obj);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			/**
			 * Updating parsed JSON data into ListView
			 * */
			adp = new AdapterSearchVietAnh(getActivity(),
					R.layout.custom_lv_vietanh, list);
			lvShowVA.setAdapter(adp);
		}

	}

	@Override
	public boolean onBackPressed() {
		HomeActivity.getInstance().setUptitle("English - Vietnamese");
		HomeActivity.getInstance().setShow();
		HomeActivity.getInstance().pusListWordFm();

		return true;
	}
}
